package com.thread.lianxi;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CarryStone {

	public static void main(String[] args) throws InterruptedException {
		ExecutorService service = Executors.newFixedThreadPool(5);
		CyclicBarrier barrier = new CyclicBarrier(5);
		CountDownLatch latch = new CountDownLatch(5);
		for (int i = 0; i < 5; i++) {
			service.execute(new Worker("壮汉"+i,barrier,latch));
		}
		service.shutdown();
		latch.await();// 等到其它线程都走完了，再走主线程。防止过早说出感谢的话来
		System.out.println("活干完了，谢谢大家！");
	}

	static class Worker implements Runnable {

		private String name;
		private CyclicBarrier barrier;
		CountDownLatch latch;

		public Worker(String name, CyclicBarrier barrier,CountDownLatch latch) {
			this.name = name;
			this.barrier = barrier;
			this.latch = latch;
		}

		@Override
		public void run() {
			try {
				System.out.println(name + " 动身了！");
				int time = (new Random()).nextInt(5000);
				Thread.sleep(time);
				System.out.println(name + "耗时" + time + "毫秒到达！等待其他人");
				barrier.await();
				latch.countDown();
				System.out.println("人已到齐！" + name + "发力了...");
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			}
		}

	}

}
